package cn.edu.zzuli.nothinglink.controller;


import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.entity.Students;
import cn.edu.zzuli.nothinglink.service.StudentsService;
import cn.edu.zzuli.nothinglink.vo.StuLoginVo;
import cn.edu.zzuli.nothinglink.vo.StuRegisterVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/stu")
public class StudentsController {

    @Autowired
    StudentsService studentsService;

    @GetMapping("/info/list")
    public R getUserList() {
        return R.success().add("stus", studentsService.list());
    }

    //这里条件查询的话，可以使用 map来接收请求题的参数,方便mybatis 参数拼接。
    @GetMapping("/info")
    public R getUserById(@RequestParam Map<String, Object> info) {
        if (info.size() == 0) return R.error().add("error", "参数有误");
        Students stu = studentsService.findOneUserByInfo(info);
        return R.success().add("stu", stu);
    }

    @DeleteMapping("/info/class/{stuId}")
    public R delStuById(@PathVariable Integer stuId) {
//        http://localhost:3100/api/stu/info/5
        if (studentsService.delStuFromTheClass(stuId)) return R.success();
        return R.error().add("error", "删除失败，请检查学生是否存在");
    }

    @DeleteMapping("/info/batch")
    public R delStus(@RequestBody JSONObject json) {
        List<Integer> stuIds = json.getJSONArray("stuIds").toJavaList(Integer.class);
        if ( stuIds != null && stuIds.size() > 0) {
            boolean res = studentsService.delbatch(stuIds);
            if (res) return R.success().setMsg("删除成功");
        }
        return R.error().add("error", "删除失败，请检查学生是否存在");
    }

    @PostMapping("/login")
    public R login(@RequestBody StuLoginVo vo) {
        if ((!StringUtils.isEmpty(vo.getUsername()) || !StringUtils.isEmpty(vo.getEmail()))
                && !StringUtils.isEmpty(vo.getPassword())) {
            return studentsService.stuLogin(vo);
        }

        return R.error().add("error", "参数错误");
    }


    @PostMapping("/register")
    public R register(@RequestBody @Valid StuRegisterVo vo) {
        return studentsService.stuRegister(vo);
    }

}

